package Users;

import Server.Server;
import ServerOutput.Output;
import Database.*;

public class UserOutputManager {
    public static String userPagePrefix = "/stats/";
    
    public static boolean isUserPage(String requestedPath) {
        return requestedPath.startsWith(userPagePrefix);
    }
    
    public static Output getUserOutput(String requestedPath) throws Exception {
        Output out = new Output();
        Stats stats = new Stats();
        if(!isUserPage(requestedPath)) {
            out.setOutputType(Server.FileTypes.none);
            out.setReturnCode(Server.ReturnCodes.NOT_FOUND_404);
            return out;
        }
        
        String strWithoutPrefix = requestedPath.replaceAll(userPagePrefix, "");
        String[] accountInfo = strWithoutPrefix.split("/");
        if(accountInfo.length != 2 && accountInfo.length != 3) {
            out.setOutputType(Server.FileTypes.none);
            out.setReturnCode(Server.ReturnCodes.NOT_FOUND_404);
            return out;
        }
        
        //out.setBytes("DEBUG User name: " + accountInfo[0] + " password: " + accountInfo[1]);
        Database DB = new Database();

        Row result = DB.queryRow("SELECT * FROM users WHERE domain='"+accountInfo[0]+"' AND password='"+ accountInfo[1] +"'");

        if (result != null) {
            
            //jeigu url yra domain/pass/reset - nuresetinam statistika ir griztam i domain/pass
            if(accountInfo.length == 3 && accountInfo[2].equals("reset")) {
                System.out.println("User " + accountInfo[0] + " requested stats reset.");
                stats.resetStatsForUser(Integer.parseInt(result.getColumnValue("id")));
                out.setBytes("<meta HTTP-EQUIV='REFRESH' content='0; url=/stats/" + accountInfo[0] + "/" + accountInfo[1] + "'>");
            } else {
                System.out.println("User " + accountInfo[0] + " connected.");
                out.setBytes(stats.getStatsHtmlForUser(Integer.parseInt(result.getColumnValue("id"))));
            }
        } else {
            out.setOutputType(Server.FileTypes.none);
            out.setReturnCode(Server.ReturnCodes.NOT_FOUND_404);
        }
        
        out.setOutputType(Server.FileTypes.textHtml);
        out.setReturnCode(Server.ReturnCodes.OK_200);
        return out;
    }
}
